import axios from "axios";
import qs from "qs";
import store from "./store";

const proxyPrefix = document.querySelector("#ApiSite").value || "/";
const apiSite = document.querySelector("#ApiSite").value || "/";
const wxSite = document.querySelector("#h5iSite").value || "/";
const networkError = "网络异常，请重试";
function isWeiXin() {
  var ua = window.navigator.userAgent.toLowerCase();
  if (ua.match(/MicroMessenger/i) == "micromessenger") {
    return true;
  } else {
    return false;
  }
}
function changeURLPar(destiny, par, par_value) {
  var pattern = par + "=([^&]*)";
  var replaceText = par + "=" + par_value;
  if (destiny.match(pattern)) {
    var tmp = "/\\" + par + "=[^&]*/";
    tmp = destiny.replace(eval(tmp), replaceText);
    return tmp;
  } else {
    if (destiny.match("[?]")) {
      return destiny + "&" + replaceText;
    } else {
      return destiny + "?" + replaceText;
    }
  }
  return destiny + "\n" + par + "\n" + par_value;
}
function GetQueryString(name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  var r = window.location.search.substr(1).match(reg); //获取url中"?"符后的字符串并正则匹配
  var context = "";
  if (r != null) context = r[2];
  reg = null;
  r = null;
  return context == null || context == "" || context == "undefined"
    ? ""
    : context;
}
// 请求拦截器
axios.interceptors.request.use(
  function(config) {
    let ts = new Date().getTime();
    let token =
      window.localStorage.getItem("user_token") ||
      GetQueryString("token") ||
      "";
    let options = {
      ts,
      token,
      format: "json"
    };

    if (process.env.NODE_ENV === "development") {
      // options.debug_mem_id = 3
    }

    if (config.headers["Content-Type"] === "multipart/form-data") {
      for (var key in options) {
        config.data.append(key, options[key]);
      }
    } else if (config.method === "get") {
      config.params = {
        ...options,
        ...config.params
      };
    } else if (config.method === "post") {
      config.data = qs.stringify({
        ...options,
        ...qs.parse(config.data)
      });
    }

    // 重置监控状态
    store.commit("RESET_STATUS");

    // 对请求数据做点什么
    return config;
  },
  function(error) {
    // 对请求错误做点什么
    return Promise.reject(error);
  }
);
// 响应拦截器
axios.interceptors.response.use(
  function(response) {
    let { data } = response;

    if (data.code === 1002) {
      window.localStorage.removeItem("user_token");
      if (isWeiXin()) {
        window.location.href = `${wxSite}/oauth/index?type=weixin&url=${
          window.location.href
        }`;
        return false;
      }
      /* global HuoSdk */
      window.localStorage.setItem("loginFlag", 1);
      // HuoSdk.login()
    } else if (data.code === 44001) {
      // 金币不足，用于金币抽奖接口 drawLottery
      data.data = {
        coin: 1
      };
    } else if (data.code !== 200) {
      store.commit("SET_FAILED_MSG", {
        msg: data.msg
      });
    } else {
      if (data.data && data.data.user_token) {
        window.localStorage.setItem("user_token", data.data.user_token);
        window.location.href = changeURLPar(window.location.href, "token", "");
      }
    }
    console.log("data111111", data);
    if (!!data.data && !!data.data.seo) {
      document.title = data.data.seo.title;
      let keywords = document.querySelector('meta[name="keywords"]');
      let description = document.querySelector('meta[name="description"]');
      keywords && keywords.setAttribute("content", data.data.seo.keyword);
      description &&
        description.setAttribute("content", data.data.seo.description);
    } else if (!!data.seo) {
      document.title = data.data.seo.title;
      let keywords = document.querySelector('meta[name="keywords"]');
      let description = document.querySelector('meta[name="description"]');
      keywords && keywords.setAttribute("content", data.data.seo.keyword);
      description &&
        description.setAttribute("content", data.data.seo.description);
    }
    // 对响应数据做点什么
    return response;
  },
  function(error) {
    store.commit("SET_FAILED_MSG", {
      msg: networkError
    });
    // 对响应错误做点什么
    return Promise.reject(error);
  }
);

export default {
  // h5wap礼包首页
  // http://doc.1tsdk.com/138?page_id=3109
  getGiftList(params, success) {
    axios.get(`${proxyPrefix}/wap/game/gift/list`, { params }).then(res => {
      if (res.data.code === 200) {
        success(res.data.data);
      }
    });
  },

  // 玩家礼包列表
  getUserGiftList(params, success) {
    axios.get(`${proxyPrefix}/wap/user/gift/list`, { params }).then(res => {
      if (res.data.code === 200) {
        success(res.data.data);
      }
    });
  },

  // 礼包详情页
  // http://doc.1tsdk.com/138?page_id=3110
  getGiftDetail(params, success) {
    axios.get(`${proxyPrefix}/wap/gift/detail`, { params }).then(res => {
      if (res.data.code === 200) {
        success(res.data.data);
      }
    });
  },

  // 礼包领取
  // http://doc.1tsdk.com/138?page_id=3218
  addGift(params, success) {
    axios.get(`${proxyPrefix}/wap/user/gift/add`, { params }).then(res => {
      if (res.data.code === 200) {
        success(res.data.data);
      } else if (res.data.code === 44001) {
        console.log(res.data);
        HuoUtils.tips(res.data.msg);
        return;
      } else if (res.data.code === 1002) {
        HuoSdk.login();
      } else {
        HuoUtils.tips(res.data.msg);
      }
    });
  },

  // 思锋h5wap首页
  // http://doc.1tsdk.com/138?page_id=6155
  getPlayIndex(success) {
    axios.get(`${proxyPrefix}/wap/home/index`).then(res => {
      if (res.data.code === 200) {
        success(res.data.data);
      }
    });
  },

  // 专题游戏列表-copy
  // http://doc.1tsdk.com/138?page_id=6140
  getGameList(params, success) {
    axios.get(`${proxyPrefix}/wap/special/games`, { params }).then(res => {
      if (res.data.code === 200) {
        success(res.data.data);
      }
    });
  },

  // H5WAP游戏列表
  // http://doc.1tsdk.com/138?page_id=3217
  searchGameList(params, success) {
    axios.get(`${proxyPrefix}/wap/game/list`, { params }).then(res => {
      if (res.data.code === 200) {
        success(res.data.data);
      }
    });
  },

  // H5-WAP开服游戏列表
  // http://doc.1tsdk.com/138?page_id=3233
  getServerList(params, success) {
    axios.get(`${proxyPrefix}/wap/gameserver/index`, { params }).then(res => {
      if (res.data.code === 200) {
        success(res.data.data);
      }
    });
  },

  // 修改昵称
  // http://doc.1tsdk.com/138?page_id=6284
  setNikename(params, success, error) {
    axios.post(`${proxyPrefix}/wap/user/nickname/update`, params).then(res => {
      if (res.data.code === 200) {
        success(res.data.msg);
      } else {
        error(res.data.msg);
      }
    });
  },

  // 修改用户头像
  // http://doc.1tsdk.com/138?page_id=3541
  setAvatar(params, success, error) {
    axios.post(`${proxyPrefix}/wap/user/avatar/update`, params).then(res => {
      if (res.data.code === 200) {
        success(res.data.msg);
      } else {
        error(res.data.msg);
      }
    });
  },

  // 修改用户密码
  // http://doc.1tsdk.com/138?page_id=3372
  changePwd(params, success, error) {
    axios.post(`${proxyPrefix}/wap/user/passwd/update`, params).then(res => {
      if (res.data.code === 200) {
        success(res.data.msg);
      } else {
        error(res.data.msg);
      }
    });
  },

  // 上传文件
  // http://doc.1tsdk.com/138?page_id=6287
  assetUpload(params, success, error) {
    let newForm = new FormData();
    newForm.append("file", params.file);
    let config = {
      headers: {
        "Content-Type": "multipart/form-data"
      }
    };
    axios.post(`${proxyPrefix}/wap/asset/upload`, newForm, config).then(res => {
      if (res.data.code === 200) {
        success(res.data.data);
      } else {
        error(res.data.msg);
      }
    });
  },

  // 发送短信
  // http://doc.1tsdk.com/138?page_id=3230
  smsSend(params, success, error) {
    axios.post(`${proxyPrefix}/wap/sms/send`, params).then(res => {
      if (res.data.code === 200) {
        success(res.data.msg);
      } else {
        error(res.data.msg);
      }
    });
  },

  // 绑定手机
  // http://doc.1tsdk.com/138?page_id=3232
  bindMobile(params, success, error) {
    axios.post(`${proxyPrefix}/wap/mobile/setpwdbybind`, params).then(res => {
      if (res.data.code === 200) {
        success(res.data.msg);
      } else {
        error(res.data.msg);
      }
    });
  },

  // 校验原有手机
  // http://doc.1tsdk.com/138?page_id=3232
  smsCheck(params, success, error) {
    axios.post(`${proxyPrefix}/wap/sms/checkold`, params).then(res => {
      if (res.data.code === 200) {
        success(res.data.msg);
      } else {
        error(res.data.msg);
      }
    });
  },

  // 获取用户信息
  // http://doc.1tsdk.com/159?page_id=4880
  getUserinfo(success) {
    axios.get(`${proxyPrefix}/wap/user/index`).then(res => {
      if (res.data.code === 200) {
        success(res.data.data);
      }
    });
  },
  // 玩家登出
  // http://doc.1tsdk.com/138?page_id=2906
  userLogout(success) {
    axios.get(`${apiSite}/v8/user/logout`).then(res => {
      if (res.data.code === 200) {
        success(res.data.data);
      }
    });
  },
  // 常见问题
  // http://doc.1tsdk.com/159?page_id=4879
  getServiceInfo(params, success) {
    axios.get(`${proxyPrefix}/wap/help/index`, { params }).then(res => {
      if (res.data.code === 200) {
        success(res.data.data);
      }
    });
  },

  // 平台消费记录列表
  getPtbConsumeList(params, success) {
    axios.get(`${proxyPrefix}/wap/order/list`, { params }).then(res => {
      if (res.data.code === 200) {
        success(res.data.data);
      }
    });
  },

  // 消息列表
  // http://doc.1tsdk.com/159?page_id=4905
  getMessageList(params, success) {
    axios.get(`${proxyPrefix}/wap/msg/list`, { params }).then(res => {
      if (res.data.code === 200) {
        success(res.data.data);
      }
    });
  },

  // 游戏详情
  // http://doc.1tsdk.com/159?page_id=4907
  getGameDetail(params, success) {
    axios.get(`${proxyPrefix}/game/detail`, { params }).then(res => {
      if (res.data.code === 200) {
        success(res.data.data);
      }
    });
  },

  // 超级签下载
  superDownUrl(params, success) {
    axios.get(`${proxyPrefix}/iossign/downurl/get`, { params }).then(res => {
      success(res.data);
    });
  },

  advertiseClickReport(params, success, error) {
    axios
      .get(`${proxyPrefix}/ad/click2`, { params })
      .then(res => {
        success(res.data);
      })
      .catch(err => {
        console.error(`广告点击上报失败: ${err}`);
        error(err);
      });
  }
};
